--[[
-- Author:      feilong
-- DateTime:    2020-10-10 17:19:33
-- Description: 
    客户端消息会由manager转达到此
--]]


local skynet = require "skynet"

local server_config = dofile(skynet.getenv("server_config"))


local table_insert = table.insert
local table_remove = table.remove
local table_unpack = table.unpack
local math_floor = math.floor
local math_random = math.random
local math_abs = math.abs




local MessageHandler = class("MessageHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor()

    self.game_session_counter = 0 --客户端唯一标识
    self.client_sessions = {} --
    self.game_session_fds = {}
    self.client_pack = new("client_pack")

    --socket状态消息
    self.socket_handler = {}

	self:register()	
end

--注册本服务里的消息
function MessageHandler:register()    
    self.message_dispatch = g.MsgDis()
    self.message_dispatch:register("start", handler(self, self.start))
    self.message_dispatch:register("instead", handler(self, self.instead))
    self.message_dispatch:register('hall.REQ_LOGIN', handler(self, self.loginReq))
end


function MessageHandler:quit()
    g.Log():debug('player is quit now!!!')
    --记录玩家下线
    if player then
        player.user_data.line_status = false
    end
    quitting = true
    --再一次检查数据是否保存
    save_data()
    if player then
        player:billlog('logout',{r = reason.ACCOUNT_LOGOUT, continue_time = continue_time})
        add_act_online_time() --增加多少在线时长
    end
    R().friendsvr(1):send('.info_mgr','update_info',curr_uid,{online = false})
    skynet.send(msg_handler,'lua','on_agent_exit',curr_uid,skynet.self())

    --退出服务
    skynet.exit()
end




---------------------------------------------------------
-- CMD
---------------------------------------------------------
function MessageHandler:start(client_info)
    g.Log():debug("agent start!", client_info)
    self.client_info = client_info
    self.uid = client_info.uid
    self.session = client_info.s
end

--账号重入
function MessageHandler:instead(client_info)
    local client_fd = self.session
    print("___client_fd__", client_fd, client_info.s)
    assert(client_fd ~= client_info.s, 'invalid insteading ' .. tostring(client_info.s))
    
    if 1 then return true end
    -- last_ping_time = util.get_now_time()
    -- print("_________ip___new_ip___", ip, new_ip)

    if client_fd > 0 then
        --让前一个client下线
        send_to_gateway('login.NTF_LOGOUT',{reason = 1,description = "异地登录"})
        local gateway_id = client_fd >> 31
        R().gateway(gateway_id):send('.watchdog','hallsvr','active_close',
            client_fd,curr_uid,R().get_source())
    else
        g.Log():debug(curr_uid,'this agent is not online')
    end
    self.client_info.s = client_info.s
    client_fd = client_info.s
    ip = new_ip
    --告诉网关本节点在监听此uid, 应该不用
    -- watch_session(client_fd,curr_uid,true)

    return true
end

--登录大厅
function MessageHandler:loginReq(msg_data)

-- message RSP_LOGIN{
--     optional string name                = 1[default = ''];
--     optional int32 gems                 = 2[default = 0];
--     optional int64 coins                = 3[default = 0];
--     optional int32 server_time          = 4[default = 0];
--     optional uint32 ping_interval       = 5[default = 0];
--     optional int32 level                = 6[default = 0];
--     optional string icon                = 7[default = '']; //假如icon以http开头，则是一个url地址，如果不是则是一个头像ID编号
--     optional int32 play_total_count     = 8[default = 0]; //总牌局数
--     optional int32 play_win_count       = 9[default = 0]; //赢牌局数
--     optional int32 sex                  = 10[default = 0]; //玩家性别,1男2女
--     optional int32 roomcards            = 11[default = 0]; //房卡数量
--     optional int32 result               = 12[default = 0];
--     optional bool can_take_newbie_award = 14[default = false]; //是否有新手奖励
--     optional bool show_signing_panel    = 15[default = false]; //是否显示签到面板
--     optional bool show_announcement     = 16[default = true]; //是否显示公告
--     optional uint32 is_review           = 17[default = 0]; //1表示是提审
--     optional uint32 forbidden_end_time  = 18[default = 0]; //账号被封结束时间
--     optional string forbidden_reason    = 19[default = '']; //账号被封原因
--     optional string description         = 20[default = ''];
--     optional string phone_code          = 21[default = '']; // 绑定的手机号
--     optional bool show_seven_announcement = 22[default = true];//是否显示周福利公告
--     optional uint32 yesterday_income    = 23[default = 0]; //周福利昨日收益
--     optional string register_channel    = 24[default = '']; //用户注册渠道
--     optional uint32 vip_level           = 25[default = 0]; //vip等级
--     optional string icon_border         = 26[default = '']; //头像框url
--     optional bool is_today_first_login  = 27[default = false]; //是否今日首次登陆
--     repeated int32 guide_list           = 28; //需要引导的游戏列表
--     optional uint32 vip_free_count      = 29[default = 0]; //大抽奖vip免费次数
--     optional bool award_open            = 30[default = true]; //大抽奖是否开启
--     optional bool has_changed_name      = 31[default = false]; //是否修改过姓名
--     optional int32 bind_gold            = 32[default = 0]; //绑定送金币
--     optional uint32 safe_box            = 33[default = 0]; //安全箱数值
--     optional uint32 shouchong_open      = 34[default = 0]; //0关闭 1开始
-- }

    print("loginReq__", msg_data)

    g.Message():sendManager("send_to_user", self.uid, "hall.RSP_LOGIN",
        {
            name = "testhall",
            coins = 1000,
            level = 1,
        })  

end




function MessageHandler:close_server()
    g.Log():debug('close_server save player data')
    local reason = "您已掉线"
    if client_fd > 0 then
        send_to_gateway('login.NTF_LOGOUT',{reason = 1,description = reason})
        local gateway_id = client_fd >> 31
        R().gateway(gateway_id):send('.watchdog','hallsvr','active_close',
            client_fd,curr_uid,R().get_source())
    else
        g.Log():debug(curr_uid,'this agent is not online')
    end    
    self:quit()
end

function MessageHandler:kick_player(reason)
    g.Log():debug("_____kick_player_____",client_fd, reason)
    if client_fd > 0 then
        send_to_gateway('login.NTF_LOGOUT',{reason = 1,description = reason})
        local gateway_id = client_fd >> 31
        R().gateway(gateway_id):send('.watchdog','hallsvr','active_close',
            client_fd,curr_uid,R().get_source())
    else
        g.Log():debug(curr_uid,'this agent is not online')
    end

    self:quit()
end

return MessageHandler